const express = require('express');
const Submission = require('../models/Submission');
const Exercise = require('../models/Exercise');
// 删除认证中间件，支持游客模式
const QianwenService = require('../src/services/qianwenService');

const router = express.Router();

// 提交写作内容进行评分
router.post('/', async (req, res) => {
  try {
    const { exerciseId, content } = req.body;
    
    // 验证题目是否存在
    const exercise = await Exercise.findById(exerciseId);
    if (!exercise || !exercise.isActive) {
      return res.status(404).json({
        success: false,
        message: '题目不存在'
      });
    }

    // 计算字数
    const wordCount = countWords(content);

    // 创建提交记录（游客模式，不关联用户）
    const submission = new Submission({
      userId: null, // 游客模式
      exerciseId,
      content,
      wordCount,
      status: 'pending'
    });

    await submission.save();

    // 异步进行AI评分
    scoreSubmissionAsync(submission._id, exercise, content);

    res.status(201).json({
      success: true,
      message: '提交成功，正在评分中...',
      data: {
        submissionId: submission._id,
        wordCount,
        status: 'pending'
      }
    });
  } catch (error) {
    console.error('提交写作错误:', error);
    
    // 处理验证错误
    if (error.name === 'ValidationError') {
      const errors = Object.values(error.errors).map(err => err.message);
      return res.status(400).json({
        success: false,
        message: errors.join('; ')
      });
    }
    
    // 处理其他错误
    res.status(500).json({
      success: false,
      message: '提交失败，请稍后重试'
    });
  }
});

// 获取提交详情和评分结果（游客模式，无需认证）
router.get('/:id', async (req, res) => {
  try {
    const submission = await Submission.findById(req.params.id)
      .populate('exerciseId', 'title content type difficulty timeLimit wordLimit')
      .populate('userId', 'username email');

    if (!submission) {
      return res.status(404).json({
        success: false,
        message: '提交记录不存在'
      });
    }

    // 游客模式，无需权限检查

    res.json({
      success: true,
      data: submission
    });
  } catch (error) {
    console.error('获取提交详情错误:', error);
    res.status(500).json({
      success: false,
      message: '获取提交详情失败'
    });
  }
});

// 获取提交历史（游客模式，显示所有公开提交）
router.get('/', async (req, res) => {
  try {
    const { 
      page = 1, 
      limit = 10, 
      sortBy = 'createdAt', 
      sortOrder = 'desc',
      exerciseId 
    } = req.query;

    // 构建查询条件（游客模式，显示所有提交）
    const query = {};

    if (exerciseId) {
      query.exerciseId = exerciseId;
    }

    // 分页参数
    const pageNum = parseInt(page);
    const limitNum = parseInt(limit);
    const skip = (pageNum - 1) * limitNum;

    // 排序参数
    const sort = {};
    sort[sortBy] = sortOrder === 'desc' ? -1 : 1;

    // 查询提交记录
    const submissions = await Submission.find(query)
      .populate('exerciseId', 'title type difficulty')
      .select('exerciseId content wordCount scores status createdAt')
      .sort(sort)
      .skip(skip)
      .limit(limitNum);

    // 获取总数
    const total = await Submission.countDocuments(query);

    res.json({
      success: true,
      data: {
        submissions,
        pagination: {
          page: pageNum,
          limit: limitNum,
          total,
          pages: Math.ceil(total / limitNum)
        }
      }
    });
  } catch (error) {
    console.error('获取提交历史错误:', error);
    res.status(500).json({
      success: false,
      message: '获取提交历史失败'
    });
  }
});

// 测试通义千问API连接
router.get('/test/qianwen', async (req, res) => {
  try {
    const qianwenService = new QianwenService();
    const isConnected = await qianwenService.testConnection();
    
    res.json({
      success: true,
      data: {
        connected: isConnected,
        message: isConnected ? '通义千问API连接正常' : '通义千问API连接失败'
      }
    });
  } catch (error) {
    console.error('测试通义千问API错误:', error);
    res.status(500).json({
      success: false,
      message: '测试通义千问API失败',
      error: error.message
    });
  }
});

// 异步评分函数
async function scoreSubmissionAsync(submissionId, exercise, content) {
  try {
    const startTime = Date.now();
    
    // 初始化通义千问服务
    const qianwenService = new QianwenService();
    
    // 调用通义千问API进行评分
    const scoringResult = await qianwenService.scoreEssay(exercise, content);
    
    const responseTime = Date.now() - startTime;

    // 更新提交记录
    await Submission.findByIdAndUpdate(submissionId, {
      scores: {
        overall: scoringResult.overall,
        taskAchievement: scoringResult.taskAchievement,
        coherence: scoringResult.coherence,
        vocabulary: scoringResult.vocabulary,
        grammar: scoringResult.grammar
      },
      feedback: scoringResult.feedback,
      strengths: scoringResult.strengths,
      improvements: scoringResult.improvements,
      aiResponseTime: responseTime,
      status: 'completed'
    });

    console.log(`✅ 提交 ${submissionId} AI评分完成，耗时 ${responseTime}ms`);
    console.log(`📊 评分结果: 总分 ${scoringResult.overall}, 任务完成 ${scoringResult.taskAchievement}, 连贯性 ${scoringResult.coherence}, 词汇 ${scoringResult.vocabulary}, 语法 ${scoringResult.grammar}`);
  } catch (error) {
    console.error(`❌ 提交 ${submissionId} AI评分失败:`, error);
    
    // 如果AI评分失败，使用默认评分
    try {
      const defaultScores = {
        overall: 6,
        taskAchievement: 6,
        coherence: 6,
        vocabulary: 6,
        grammar: 6
      };

      await Submission.findByIdAndUpdate(submissionId, {
        scores: defaultScores,
        feedback: 'AI评分服务暂时不可用，已为您提供基础评分。建议稍后重试获取详细反馈。',
        strengths: ['作文结构清晰', '语言表达基本准确'],
        improvements: ['建议增加更多细节支撑', '可以尝试使用更丰富的词汇', '注意语法准确性'],
        aiResponseTime: Date.now() - Date.now(),
        status: 'completed'
      });

      console.log(`⚠️ 提交 ${submissionId} 使用默认评分完成`);
    } catch (updateError) {
      console.error(`❌ 更新提交 ${submissionId} 状态失败:`, updateError);
      
      // 最后更新状态为失败
      await Submission.findByIdAndUpdate(submissionId, {
        status: 'failed',
        feedback: '评分服务暂时不可用，请稍后重试'
      });
    }
  }
}

// 字数统计函数
function countWords(text) {
  if (!text) return 0;
  return text.trim().split(/\s+/).filter(word => word.length > 0).length;
}

module.exports = router;
